from common.database import runSql
from flask import Blueprint, request

from model.comment import comment, db as commentDb
from model.User import User, db as userDb
from utils.JsonUtil import to_json_all  # 转json
from utils.Result import Response  # 统一返回工具类
import datetime
from sqlalchemy import desc
import json

# 蓝图名
comment_blueprint = Blueprint('comment', __name__)
# 创建工具类实例
Result = Response()


@comment_blueprint.route('/getCommentByPlantId', methods=['GET'])
def getCommentByPlantId():
    plantId = request.args.get("plantId")
    commentList = comment.query.filter(comment.plant_id == plantId).all()
    if not commentList:
        return {"code": 200, "data": [], "message": "成功"}
    for comments in commentList:
        comments.create_time = comments.create_time.strftime('%Y-%m-%d %H:%M:%S')
        user = User.query.filter(User.id == comments.user_id).first()
        comments.user_id = user.nick_name
    jsonData = to_json_all(commentList)
    return Result.success(jsonData)


# 添加评论
@comment_blueprint.route('/add', methods=['POST'])
def addComment():
    # 获取 POST 请求的 JSON 数据
    data = request.get_json()
    # 获取具体字段
    userId = data['userId']
    content = data['content']
    plantId = data['plantId']

    # 注册添加数据
    commentData = comment(
        content=content,
        plant_id=plantId,
        user_id=userId,
        create_time=datetime.datetime.now()
        )
    # 通过session进行commit提交修改
    commentDb.session.add(commentData)  # 先添加
    commentDb.session.commit()  # 后提交

    return Result.success("添加成功")


# 刪除文章
@comment_blueprint.route('/delete')
def deletePlant():
    # 通過id刪除plant表
    id = request.args.get("id")
    commentDb.session.query(comment).filter(comment.id == id).delete()
    commentDb.session.commit()
    commentDb.session.close()
    return Result.success("刪除成功")